package com.spa.infrastructure.service.sms.huaxin;

import cn.hutool.core.util.RandomUtil;
import com.spa.infrastructure.service.HttpService;
import com.spa.infrastructure.service.sms.ApplicationConfiguration;
import com.spa.infrastructure.service.sms.SmsProvider;
import com.spa.infrastructure.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class HuaXinSmsService implements SmsProvider {

    @Autowired
    private HttpService httpService;

    @Autowired
    private ApplicationConfiguration smsConfig;

    @Resource
    private RedisUtil redisUtil;

    @Value("${huaXin.userId}")
    private String UserId;

    @Value("${huaXin.account}")
    private String account;

    @Value("${huaXin.password}")
    private String password;

    public String send(String phone, String content) {
        String url = "https://dx.ipyy.net/smsJson.aspx?action=send&userid=" + UserId + "&account=" + account + "&password="
                + password + "&mobile=" + phone + "&content=" + content;
        log.info("phone : {} content : {}", phone, content);
        String result = httpService.sendPost(url, null, null);
        log.info("result : {}", result);
        return result;
    }

    @Override
    public void sendVerificationCode(String phoneNumber, String key) {
        if(phoneNumber == null) {
            return ;
        }
        /* 默认验证码 */
        String smsCode = smsConfig.getDefaultCode();
        // 如果是测试模式，则不真正发送短信，模拟成功即可
        if (smsConfig.isFlagSendSms()) {
            /* 构造随机验证码 */
            smsCode = RandomUtil.randomNumbers(6);
            send(phoneNumber, HuaXinUtil.template6(smsCode));
        }
        /* 如果是验证码，则需要将验证码存入缓存 */
        redisUtil.set(key,smsCode,smsConfig.getCodeTimeout()* 60L);
    }

    @Override
    public void sendNotice(String phoneNumber, String content) {
        if(phoneNumber == null) {
            return;
        }
        // 如果是测试模式，则不真正发送短信，模拟成功即可
        if (smsConfig.isFlagSendSms()) {
            send(phoneNumber, content);
        }
    }
}
